"use strict";
$jq.namespace('PeopleMedia.CP');

PeopleMedia.CP.LoginManager = function () {
    this._siteId = null;
    this._emailGUID = "";
    this._loginButtonFieldname = "btnLogin";
    this._loginProcess = null;
    this._onLoginSuccess = null;
    this._loginPanelId = "divLogin";
    this._usernameFieldname = "txtLoginUsername";
    this._passwordFieldname = "txtLoginPassword";
    this._memberId = null;
    this._loginData = null;
    this._rememberMeFieldname = "chkRememberMe";
};

PeopleMedia.CP.LoginManager.prototype = {
    Oid: "PeopleMedia.CP.LoginManager-v1.1",
    SiteId: function (siteId) {
        if (arguments.length > 0) {
            this._siteId = siteId;
        } else {
            return this._siteId;
        }
    },
    EmailGUID: function (emailGUID) {
        if (arguments.length > 0) {
            this._emailGUID = emailGUID;
        } else {
            return this._emailGUID;
        }
    },
    RememberMeFieldname: function (name) {
        if (arguments.length > 0) {
            this._rememberMeFieldname = name;
        } else {
            return this._rememberMeFieldname;
        }
    },
    LoginButtonFieldname: function (name) {
        if (arguments.length > 0) {
            this._loginButtonFieldname = name;
        } else {
            return this._loginButtonFieldname;
        }
    },
    LoginProcess: function (process) {
        if (arguments.length > 0) {
            this._loginProcess = process;
        } else {
            return this._loginProcess;
        }
    },
    OnLoginSuccess: function (onLoginSuccess) {
        if (arguments.length > 0) {
            this._onLoginSuccess = onLoginSuccess;
        } else {
            return this._onLoginSuccess;
        }
    },
    LoginPanelId: function (loginPanelId) {
        if (arguments.length > 0) {
            this._loginPanelId = loginPanelId;
        } else {
            return this._loginPanelId;
        }
    },
    LoginPanel: function () {
        return $jq("#" + this.LoginPanelId());
    },
    UsernameFieldname: function (name) {
        if (arguments.length > 0) {
            this._usernameFieldname = name;
        } else {
            return this._usernameFieldname;
        }
    },
    Username: function () {
        return $jq("#" + this.UsernameFieldname()).val();
    },
    PasswordFieldname: function (name) {
        if (arguments.length > 0) {
            this._passwordFieldname = name;
        } else {
            return this._passwordFieldname;
        }
    },
    Password: function () {
        return $jq("#" + this.PasswordFieldname()).val();
    },
    MemberId: function (memberId) {
        if (arguments.length > 0) {
            this._memberId = memberId;
        } else {
            return this._memberId;
        }
    },
    LoginData: function () {
        return this._loginData;
    },
    initialize: function (currentQueryString) {
        try {
            this.SiteId(PeopleMedia.CP.SiteID());
            var keyValues = PeopleMedia.Net.getQueryString(currentQueryString);
            var emailGUID = PeopleMedia.Net.getQueryStringValue(keyValues, "EmailGUID");
            if (typeof (emailGUID) !== 'undefined' && emailGUID !== null && emailGUID.length == 36) {
                this.EmailGUID(emailGUID);
            }

            this.initKeepMeLoggedInCheckbox();
            this.isRememberMeChecked();
            var loginButtonName = this.LoginButtonFieldname();
            if (loginButtonName != undefined && loginButtonName != null && $jq('#' + loginButtonName)) {
                var process = this.LoginProcess();
                if (process == undefined || process == null) {
                    var thisObj = this;
                    process = function () {
                        thisObj.standardLoginProcess();
                    };
                }
                $jq('#' + loginButtonName).bind('click', function () {
                    process();
                });
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"initialize" });
        }
    },
    login: function (onSuccess, onFailure) {
        try {
            var errors = this.validate();
            if (errors.length > 0) {
                onFailure(errors);
                return;
            }

            var username = this.Username();
            var password = this.Password();

            var cpsessionid = PeopleMedia.CP.SessionId();

            if (typeof (cpsessionid) === "undefined" || cpsessionid === "undefined" || !PeopleMedia.CP.Utilities.isGuid(cpsessionid)) {
                try {
                    var logMsg = "Invalid session id in login-v1.1:login(): PeopleMedia.CP.SessionId()=";
                    if (typeof (cpsessionid) === "undefined") {
                        logMsg += "{undefined object}";
                    } else {
                        logMsg += cpsessionid;
                    }
                    logMsg += "; document.cookie=" + document.cookie;
                    PeopleMedia.CP.logMessage(logMsg);
                }
                catch (ex) {
                    PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"login invalid session" });
                }
                cpsessionid = "";
            }

            var url = PeopleMedia.CP.getPMApiBaseUrl("AuthenticateMemberCP");
            url += "&communityNameOrID=" + this.SiteId();
            url += "&memberUsername=" + username;
            url += "&memberPassword=" + password;
            url += "&sponsorID=" + PeopleMedia.CP.SponsorID();
            url += "&visitorID=" + PeopleMedia.CP.VisitorID();
            url += "&cpSessionID=" + cpsessionid;
            if (this.EmailGUID().length > 0) {
                url += "&emailGUID=" + this.EmailGUID();
            }
            url += "&callbackmethod=?";

            PeopleMedia.CP.ui_busy();

            var thisObj = this;
            this.setRememberMeChecked(username);
            var startTime = new Date().getTime();
            var timeoutValue = 30000;
            jQuery.ajax({
                type: "GET",
                url: url,
                dataType: "json",
                success: function (data) {
                    thisObj.login_complete(onSuccess, onFailure, data);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    var endTime = new Date().getTime();
                    var duration = (endTime - startTime);
                    var data = PeopleMedia.CP.convertAjaxErrorToFault(jqXHR, textStatus, errorThrown);
                    if (!data.IsCancelled) {
                        PeopleMedia.CP.logAjaxError("Ajax request failure", url, { oid: thisObj.Oid, method: "login", duration: duration }, jqXHR, textStatus, errorThrown, function (jqXHR, textStatus) {
                        });
                    }
                    thisObj.login_complete(onSuccess, onFailure, data);
                },
                async: true,
                cache: false,
                timeout: timeoutValue
            });
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"login" });
        }
    },
    login_complete: function (onSuccess, onFailure, data) {
        try {
            var errors = [];
            PeopleMedia.CP.ui_done();
            if (data.Fault) {
                if (!data.Fault.IsCancelled) {
                    errors.push(PeopleMedia.CP.convertFaultToError(data.Fault));
                }
                onFailure(errors);
            } else {
                this._loginData = data;
                PeopleMedia.CP.Services.persistCookies(data);
                this.incrementIsRegisteredLoginCounter();
                this.updateKeepMeLoggedInCookieFromCheckbox();
                onSuccess(data);
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "login_complete" });
        }
    },
    validate: function () {
        var errors = [];

        try {
            var username = this.Username();
            var password = this.Password();

            if (username == null || username == '') {
                errors.push({ Field: this.UsernameFieldname(), Text: PeopleMedia.CP.ClientMessages.LoginHandle });
            }

            if (password == null || password == '') {
                errors.push({ Field: this.PasswordFieldname(), Text: PeopleMedia.CP.ClientMessages.LoginPassword });
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"validate" });
        }

        return errors;
    },
    standardLoginProcess: function () {
        try {
            var thisObj = this;
            $jq("#" + this.LoginButtonFieldname()).fadeTo('fast', '0.3');
            this.login(
                function (data) {
                    thisObj.standardLoginProcess_onSuccess(data);
                },
                function (errors) {
                    thisObj.standardLoginProcess_onFailure(errors);
                }
            );
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"standardLoginProcess" });
        }
    },
    standardLoginProcess_onSuccess: function (data) {
        try {
            var thisObj = this;
            this.MemberId(data.Identifier);
            var onLoginSuccess = this.OnLoginSuccess();
            if (onLoginSuccess == undefined || onLoginSuccess == null) {
                onLoginSuccess = function (sender, data) {
                    thisObj.standardOnLoginSuccess(thisObj, data);
                };
            }
            onLoginSuccess(this, data);
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "standardLoginProcess_onSuccess" });
        }
    },
    standardLoginProcess_onFailure: function (errors) {
        try {
            var firstError = PeopleMedia.CP.getFirstError(errors);
            if (firstError && firstError.IsAjaxError) {
                PeopleMedia.CP.gotoSite('/v3/login');
            } else {
                $jq("#" + this.LoginButtonFieldname()).fadeTo('fast', '1.0');
                PeopleMedia.CP.Messaging.show(errors);
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"standardLoginProcess_onFailure" });
        }
    },
    standardOnLoginSuccess: function (sender, data) {
        try {
            PeopleMedia.CP.gotoSite(data.AutoLoginUrl);
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"standardOnLoginSuccess" });
        }
    },
    isKeepMeLoggedInFeatureEnabled: function() {
        try {
            if ($jq('#chkKeepMeLoggedIn').length <= 0) {
                return false;
            } else {
                return PeopleMedia.CP.PersistentLoginEnabled();
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"isKeepMeLoggedInFeatureEnabled" });
        }
    },
    isKeepMeLoggedInCookieEnabled: function () {
        var enabled = true;
        try {
            var plid = PeopleMedia.Net.readCookie('PLID');
            if (plid !== undefined && plid !== null) {
                if (plid === 'OFF=1' || plid['OFF'] === '1') {
                    enabled = false;
                }
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "isKeepMeLoggedInCookieEnabled" });
        }
        return enabled;
    },
    initKeepMeLoggedInCheckbox: function() {
        try {
            if (this.isKeepMeLoggedInFeatureEnabled()) {
                $jq('#pnlRememberMe').hide();
                $jq('#pnlKeepMeLoggedIn').show();
            }
            else {
                $jq('#pnlKeepMeLoggedIn').hide();
                $jq('#pnlRememberMe').show();
                return;
            }

            var checked = this.isKeepMeLoggedInCookieEnabled();
            $jq('#chkKeepMeLoggedIn').attr('checked', checked);
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"initKeepMeLoggedInCheckbox" });
        }
    },
    updateKeepMeLoggedInCookieFromCheckbox: function () {
        try {
            var enabled = ($jq('#chkKeepMeLoggedIn:checked').length > 0);
            this.updateKeepMeLoggedInCookie(enabled);
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "updateKeepMeLoggedInCookieFromCheckbox" });
        }
    },
    updateKeepMeLoggedInCookie: function (enabled) {
        try {
            if (!this.isKeepMeLoggedInFeatureEnabled()) {
                return;
            }
            var id = "";
            var plid = PeopleMedia.Net.readCookie('PLID');
            if (enabled && plid !== undefined && plid !== null) {
                if (plid['ID'] !== undefined && plid['ID'] !== null) {
                    id = plid['ID'];
                }
            }

            PeopleMedia.Net.createCookie('PLID', 'OFF=' + ((enabled) ? '0' : '1') + '&ID=' + id, 365);
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "updateKeepMeLoggedInCookie", enabled: enabled });
        }
    },
    setRememberMeChecked: function (name) {
        try {
            var obj = document.getElementById('chkRememberMe');
            if (obj != null) {
                if (document.getElementById('chkRememberMe').checked) {
                    PeopleMedia.Net.createCookie('MRUN', name, 30);
                } else {
                    PeopleMedia.Net.createCookie('MRUN', '', -1);
                }
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"setRememberMeChecked" });
        }
    },
    isRememberMeChecked: function () {
        try {
            if (document.getElementById('chkRememberMe') != null && document.getElementById('txtLoginUsername') != null) {
                var mrun = PeopleMedia.Net.readCookie('MRUN');
                if (typeof (mrun) !== 'undefined' && mrun != null && mrun.length > 0) {
                    document.getElementById('txtLoginUsername').value = mrun;
                    document.getElementById('chkRememberMe').checked = true;
                }
            }
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"isRememberMeChecked" });
        }
    },
    getMemberIdCookie: function () {
        try {
            var mrid = PeopleMedia.Net.readCookie('MRID');
            if (mrid == undefined) {
                mrid = null;
            }
            return mrid;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"getMemberIdCookie" });
            return null;
        }
    },
    hasLoggedIntoSite: function () {
        try {
            var mrid = this.getMemberIdCookie();
            var hasLoggedIn = mrid != null && mrid.length > 0;
            return hasLoggedIn;
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"hasLoggedIntoSite" });
            return false;
        }
    },
    incrementIsRegisteredLoginCounter: function () {
        try {
            var counter = PeopleMedia.Net.readCookie('IsRegisteredLoginCounter');
            var loginCount = (counter != null) ? parseInt(counter, 10) : 0;
            if (isNaN(loginCount)) {
                loginCount = 0;
            }
            loginCount++;
            PeopleMedia.Net.createCookie('IsRegisteredLoginCounter', loginCount.toString());
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid: this.Oid, method: "incrementIsRegisteredLoginCounter" });
            return false;
        }
    },
    isAutoLoginAvailable: function (currentQueryString) {
        try {
            var keyValues = PeopleMedia.Net.getQueryString(currentQueryString);
            var loginQS = PeopleMedia.Net.getQueryStringValue(keyValues, "login");
            if (typeof (loginQS) === 'undefined' || loginQS === null || loginQS.length <= 2) {
                return false;
            }
            return PeopleMedia.CP.AutoLoginEnabled();
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"isAutoLoginAvailable" });
            return false;
        }
    },
    autoLogin: function () {
        try {
            if (!this.isAutoLoginAvailable()) {
                return;
            }
            PeopleMedia.CP.gotoSite("/v3/autologin?lpsal=true");
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"autoLogin" });
        }
    },
    isLoggedIntoSite: function (callback) {
        try {
            if (!this.hasLoggedIntoSite()) { // fast check
                callback(false, null);
            }
            var thisObj = this;
            var domainName = PeopleMedia.CP.DomainName();
            if (domainName.split('.').length <= 2) {
                domainName = PeopleMedia.CP.Subdomain() + "." + PeopleMedia.CP.DomainName();
            }
            var url = 'http://' + domainName.toLowerCase() + '/v3/lps/signinstatus?callback=?';
            var startTime = new Date().getTime();
            var timeoutValue = 30000;
            jQuery.ajax({
                type: "GET",
                url: url,
                dataType: "json",
                success: function (data) {
                    thisObj.isLoggedIntoSite_complete(callback, data);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    var endTime = new Date().getTime();
                    var duration = (endTime - startTime);
                    var data = PeopleMedia.CP.convertAjaxErrorToFault(jqXHR, textStatus, errorThrown);
                    if (!data.IsCancelled) {
                        PeopleMedia.CP.logAjaxError("Ajax request failure", url, { oid: thisObj.Oid, method: "isLoggedIntoSite", duration: duration }, jqXHR, textStatus, errorThrown, function (jqXHR, textStatus) {
                        });
                    }
                    data.SignInStatus = null;
                    thisObj.isLoggedIntoSite_complete(callback, data);
                },
                async: true,
                cache: false,
                timeout: timeoutValue
            });
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"isLoggedIntoSite" });
        }
    },
    isLoggedIntoSite_complete: function (callback, data) {
        try {
            var mrid = this.getMemberIdCookie();
            callback(data.SignInStatus, mrid);
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"isLoggedIntoSite_complete" });
        }
    },
    gotoSiteIfLoggedIn: function () {
        try {
            this.isLoggedIntoSite(function (status) {
                if (status) {
                    PeopleMedia.CP.gotoSite("/v3/home");
                }
            });
        }
        catch (ex) {
            PeopleMedia.CP.handleException(ex, { oid:this.Oid, method:"gotoSiteIfLoggedIn" });
        }
    }
};
